package nl.runnable.solr.xslt;

import java.util.HashMap;
import java.util.Map;

import org.apache.solr.common.util.NamedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Factory for creating {@link TemplatesResolver}. This implementation creates {@link DefaultTemplatesResolver}
 * instances.
 * 
 * @author Laurens Fridael
 * 
 */
public class TemplatesResolverFactory {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * Instantiates and configures a {@link DefaultTemplatesResolver} according to the given {@link NamedList}.
	 * 
	 * @param configuration
	 */
	public TemplatesResolver createTemplatesResolver(final NamedList<String> configuration) {
		final DefaultTemplatesResolver templatesResolver = new DefaultTemplatesResolver();
		logger.debug("Creating {}", templatesResolver.getClass());
		final String defaultStylesheet = configuration.get(ConfigurationSettings.DEFAULT_STYLESHEET);
		if (defaultStylesheet != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Configuring default stylesheet: {}", defaultStylesheet);
			}
			templatesResolver.setDefaultStylesheet(defaultStylesheet);
		}
		final String stylesheetPrefix = configuration.get(ConfigurationSettings.STYLESHEET_PREFIX);
		if (stylesheetPrefix != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Configuring stylesheet prefix: {}", stylesheetPrefix);
			}
			templatesResolver.setStylesheetPrefix(stylesheetPrefix);
		}
		final String stylesheetSuffix = configuration.get(ConfigurationSettings.STYLESHEET_SUFFIX);
		if (stylesheetSuffix != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Configuring stylesheet suffix: {}", stylesheetPrefix);
			}
			templatesResolver.setStylesheetSuffix(stylesheetSuffix);
		}
		final Map<QualifiedName, String> stylesheetsByRootElementName = new HashMap<QualifiedName, String>();
		templatesResolver.setStylesheetsByRootElementName(stylesheetsByRootElementName);
		final boolean disableStylesheetCache = Boolean.TRUE.equals(configuration
				.get(ConfigurationSettings.DISABLE_STYLESHEET_CACHE));
		templatesResolver.setDisableStylesheetCache(disableStylesheetCache);
		final boolean disableRootElementScan = Boolean.TRUE.equals(configuration
  		.get(ConfigurationSettings.DISABLE_ROOT_ELEMENT_SCAN));
  	templatesResolver.setDisableRootElementScan(disableRootElementScan);
		return templatesResolver;
	}

}
